-- UIPetRecruitMain
-- Create by cheny3
-- 冈布奥招募界面

require "game/ui/form/shop/UITankDesc"
require "game/ui/form/shop/UIPetRecruit"

-- UIPetRecruitMain继承自Layer
UIPetRecruitMain = class("UIPetRecruitMain", function()
    return cc.Layer:create();
end);

function UIPetRecruitMain.create()
    return UIPetRecruitMain.new();
end

-- 内部函数声明
local campType = {2, 1, 3, 4};

-- 构造函数
function UIPetRecruitMain:ctor()
    -- 初始化
    self:setName("UIPetRecruitMain");
    -- 招募模板
    local node = cc.CSLoader:createNode("layout/shop/PetRecruitMain.csb");
    self:addChild(node);
    self.node = node;

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 播放出现弹出动画
function UIPetRecruitMain:playAppearEffect()
    -- 锁屏
    wait(0.5);

    -- 阵营弹出顺序
    local campList = {2, 4, 3, 1};
    for index, campId in pairs(campList) do
        local node = findChildByName(self.node, "bg2/camp" ..  campId);
        node:setScale(0);
        local scaleUp = cc.ScaleTo:create(0.3, 1.1);
        local scaleDown = cc.ScaleTo:create(0.1, 1.0);
        local delay = cc.DelayTime:create((index - 1) * 0.05);
        node:runAction(cc.Sequence:create(delay, scaleUp, scaleDown));
    end
end

-- 适配
function UIPetRecruitMain:resize()
    local w = AlignM.frameSize.width;
    local h = AlignM.frameSize.height;

    local node = self.node;

    -- bg2居中显示
    -- 为了和UIPetRecruit产生互动/适配
    AlignM.alignToCenter(node, "bg2");

    -- 每个阵营名字
    for _, campId in pairs(campType) do
        local campNode = findChildByName(node, "bg2/camp" .. campId);
        local offSet = math.max(h / w - 1.5, 0) * 300;
        campNode:setPositionY(campNode:getPositionY() + offSet);
    end

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- TOP顶部居中并缩放至合适大小
    AlignM.alignToTopCenter(node, "TOP");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- camp图标点击后效果
function UIPetRecruitMain:playCampFlyEffect(campId)
    -- 锁屏
    wait(0.5);

    -- 打开雇佣界面
    UIMgr.getCurrentScene():removeFormByName("UIPetRecruit");
    local uiForm = UIPetRecruit.create(campId);

    local mask1 = findChildByName(uiForm.node, "CT/left_mask");
    local mask2 = findChildByName(uiForm.node, "CT/right_mask");
    mask1:setVisible(false);
    mask2:setVisible(false);
    local function delayMask()
        mask1:setVisible(true);
        mask2:setVisible(true);
    end
    performWithDelay(self, delayMask, 0.8);

    -- 设置透明度
    local function setNodeOpacity(node, value)
        -- 递归调用
        for _, childNode in pairs(node:getChildren()) do
            if childNode:getName() ~= "TOP" and childNode:getName() ~= "BT" then
                setNodeOpacity(childNode, value);
                node:setCascadeOpacityEnabled(true);
                node:setOpacity(value);
            end
        end
    end

    -- 设置淡入淡出按钮
    local function nodeFadeEffect(node, fadeType)
        -- 递归调用
        for _, childNode in pairs(node:getChildren()) do
            if childNode:getName() == "TOP"
                or childNode:getName() == "BT" then
                if fadeType == "fadeOut" then
                    childNode:setVisible(false);
                else
                    childNode:setVisible(true);
                end
            else
                nodeFadeEffect(childNode, fadeType);
                local fadeEffect;

                if fadeType == "fadeOut" then
                    fadeEffect = cc.FadeOut:create(0.8);
                else
                    fadeEffect = cc.FadeIn:create(0.8);
                end
                node:runAction(fadeEffect);
            end
        end
    end

    setNodeOpacity(uiForm.node, 0);
    UIMgr.getCurrentScene():addForm(uiForm);

    local campNode = findChildByName(self.node, "bg2/camp" .. campId);
    local campName = findChildByName(campNode, "name");
    local campSlime = findChildByName(campNode, "slime");
    campName:setVisible(false);
    campSlime:setVisible(false);

    -- 移动到中心位置
    local moveTo = cc.MoveTo:create(0.3, cc.p(383.5, 701));
    local scaleUp = cc.ScaleTo:create(0.3, 2.35);
    campNode:runAction(moveTo);
    campNode:runAction(scaleUp);

    -- 两个界面节点的所有子节点淡入淡出
    nodeFadeEffect(uiForm.node, "fadeIn");
    nodeFadeEffect(self.node, "fadeOut");
end

-- 重绘
function UIPetRecruitMain:redraw()
    local titleNode = findChildByName(self.node, "TOP/title_node");
    local titleLabel = findChildByName(titleNode, "title_label");
    -- 主标题
    TextStyleM.setArtWordTitleStyle(titleLabel);
    titleLabel:setString(getLocStr("pet_recruit_title"));

    -- 每个阵营名字
    for _, campId in pairs(campType) do
        local campNode = findChildByName(self.node, "bg2/camp" .. campId);
        local nameLabel = findChildByName(campNode, "name");
        local name = CampM.query(campId, "name");
        local slimeNode = findChildByName(campNode, "slime");

        TextStyleM.setOutlineStyle(nameLabel, 3);
        TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_ORANGE, true, -4, nil, nil, nil, nil, true);
        nameLabel:setString(name);

        local petId = PetShopM.getCanHireSlimeByCamp(campId);
        if petId > 0 then
            slimeNode:setVisible(true);
            local bubbleNode = findChildByName(slimeNode, "bubble");
            local slimeImg = findChildByName(slimeNode, "img");
            slimeImg:loadTexture(getHeroIconPath(petId));
            if not slimeImg.breath then
                playSlightAnima(slimeImg);
                slimeImg.breath = true;
            end
            -- 不再显示气泡
            bubbleNode:setVisible(false);
        else
            slimeNode:setVisible(false);
        end

        -- 点击
        local function onClickImg(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                self:playCampFlyEffect(campId);
                AudioM.playFx("cosmmic_gate1");
            end
        end
        campNode:addTouchEventListener(onClickImg);
        local effectNode = findChildByName(campNode, "effect");
        effectNode:stopAllActions();
        effectNode:removeAllChildren();
        local effectList = {1287, 1286, 1288, 1289};
        local _, effect = playEffect(effectNode, effectList[campId], 0, -4);
        effect:setOpacity(255);
    end
end

-- 显示/隐藏底部BUTTON
function UIPetRecruitMain:showBottomBotton(visible)
    local BT = findChildByName(self.node, "BT");
    BT:setVisible(visible);
end

-- 注册事件处理回调函数
function UIPetRecruitMain:registerEventCallback()
    -- 注册获得焦点的回调
    EventMgr.register("UIPetRecruitMain", event.FOCUS_CHANGED, function(para)
        if para["get"] == "UIPetRecruitMain" then
            UIMgr:getCurrentScene().topMenu:show(TOPMENU_FRAME_MONEY, TOPMENU_FRAME_GEM);
            self:showBottomBotton(true);
        elseif para["lose"] == "UIPetRecruitMain"
            and para["get"] ~= "UIInvisibleForm" then
            self:showBottomBotton(false);
        end
    end);

    -- 活动开始事件
    EventMgr.register("UIPetRecruitMain", event.ACTIVITY_CHANGE, function(args)
        local id = args["id"];
        if ActivityM.query(id, "rule") ~= "dungeon" then
            -- 不是地面迷宫
            return;
        end

        -- 重绘
        self:redraw();
    end);

    -- 活动结束事件
    EventMgr.register("UIPetRecruitMain", event.ACTIVITY_CLOSE, function(args)
        local id = args["id"];
        if ActivityM.query(id, "rule") ~= "dungeon" then
            -- 不是地面迷宫
            return;
        end

        -- 重绘
        self:redraw();
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            cclog("UIPetRecruitMain 界面析构清理");
            EventMgr.removeAll("UIPetRecruitMain");
        elseif eventType == "enter" then
            -- 播放弹出效果
            self:playAppearEffect();
        end
    end);
end

-- 注册点击事件
function UIPetRecruitMain:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIPetRecruitMain");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 说明按钮
    local btnDesc = findChildByName(self.node, "BT/btn_desc");
    local function onDescClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            local extra = {
                ["name"]   = getLocStr("pet_recruit_title"),
                ["desc"]   = getLocStr("pet_recruit_desc1") .. getLocStr("pet_recruit_desc2") .. getLocStr("pet_recruit_desc3"),
                ["detail"] = getLocStr("pet_recruit_detail"),
            };
            local uiTankDesc = UITankDesc.create(nil, nil, extra);
            UIMgr.getCurrentScene():addForm(uiTankDesc);
            -- 音效
            AudioM.playFx("workshop_material");
        end
    end
    btnDesc:addTouchEventListener(onDescClick);
    TextStyleM.setTextStyle(btnDesc, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnDesc:setTitleText(getLocStr("btn_text_help"));
end